package chen.web.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Map;
import java.util.UUID;

import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import chen.web.config.ConfigRepository;
import chen.web.config.SiteConfig;
import chen.web.util.PathUtil;

@Controller
public class FileUpload {
	
	private static final String[] AllowSuffix = {"gif", "jpg", "jpeg", "png"};
	
	//xheditor上传图片
	@RequestMapping(value="/xheditor/upload", method=RequestMethod.POST)
	public @ResponseBody String uploadImageForXhEditor(@RequestParam("filedata") MultipartFile mFile, MultipartHttpServletRequest request) throws IOException, JSONException{
		ModelAndView mav = uploadImageForEditor(mFile, request);
		String type = (String) mav.getModel().get("type");
		String message = (String) mav.getModel().get("message");
		String fileURI = (String) mav.getModel().get("fileURI");
		
		JSONObject json = new JSONObject();
		if("uploadFailureForEditor".equals(type)){
			json.put("msg", "");
			json.put("err", message);
		}else {
			json.put("msg", ConfigRepository.instance().get(SiteConfig.class).getBaseURL()+fileURI);
			json.put("err", "");
		}
		return json.toString();
	}
	
	@RequestMapping(value="/editor/upload", method=RequestMethod.POST)
	public ModelAndView uploadImageForEditor(@RequestParam("imgFile") MultipartFile mFile, MultipartHttpServletRequest request) throws IOException{
		ModelAndView mav = new ModelAndView("message");
		if(mFile.isEmpty()){
			mav.addObject("type", "uploadFailureForEditor");
			mav.addObject("message", "图片上传失败");
			return mav;
		}
		
		int length = request.getContentLength();
		if(length > 1024 * 1024 * 2){
			mav.addObject("type", "uploadFailureForEditor");
			mav.addObject("message", "图片大小不能超过2M");
			return mav;
		}
		
		
		String originalFilename = mFile.getOriginalFilename();
		String suffix = getSuffix(originalFilename);
		int i = Arrays.binarySearch(AllowSuffix, suffix);
		if(i == -1){
			mav.addObject("type", "uploadFailureForEditor");
			mav.addObject("message", "不能上传这种格式的图片");
			return mav;
		}
		
		String filePath = new StringBuffer().append(PathUtil.getAppDirectory().getPath()) 
											.append(File.separatorChar)
											.append("static")
											.append(File.separatorChar)
											.append("upload")
											.append(File.separatorChar)
											.append("images")
											.append(File.separatorChar)
											.append(Calendar.getInstance().get(Calendar.YEAR))
											.append(Calendar.getInstance().get(Calendar.MONTH+1))
											.append(File.separatorChar)
											.append(UUID.randomUUID().toString())
											.append(".")
											.append(suffix)
											.toString();
		byte[] bytes = mFile.getBytes();
		File file = new File(filePath);
		file.getParentFile().mkdirs();
		FileOutputStream fos = new FileOutputStream(file);
		fos.write(bytes);
		fos.flush();
		fos.close();
		
		Map<String, String> params = request.getParameterMap();
		mav.addObject("type", "uploadSuccessForEditor");
		mav.addAllObjects(params);
		mav.addObject("fileURI", toURI(filePath));
		return mav;
	}
	
	
	/**
	 * 将本地文件系统地址转换为URI地址
	 * @param filePath	本地文件系统地址
	 * @return	URI地址
	 */
	private String toURI(String filePath){
		int index = filePath.lastIndexOf(File.separatorChar + "static");
		if(index == -1){
			throw new IllegalArgumentException("文件路径必须在static下");
		}
		String str = filePath.substring(index, filePath.length());
		return str.replace(File.separatorChar, '/');
	}
	
	/**
	 * 得到后缀名
	 * @param fileName
	 * @return 返回小写的后缀名，如果没有后缀名返回null
	 */
	private String getSuffix(String fileName){
		String suffix = null;
		int index = fileName.lastIndexOf('.');
		if(index != -1){
			suffix = fileName.substring(index+1, fileName.length());
		}
		if(suffix != null){
			suffix = suffix.toLowerCase();
		}
		return suffix;
	}
	
}
